package org.familysearch.fsapi.gwt.server.bo;

import java.util.ArrayList;

import org.familysearch.fsapi.gwt.common.Logger;
import org.familysearch.fsapi.gwt.common.client.entities.Temple;
import org.familysearch.fsapi.gwt.server.dao.DAOException;
import org.familysearch.fsapi.gwt.server.dao.DAOFactory;
import org.familysearch.fsapi.gwt.server.dao.Session;
import org.familysearch.fsapi.gwt.server.dao.TempleDAO;

public class TempleBO {

	private IdentityBO identityBO = new IdentityBO();
	private DAOFactory daoFactory = DAOFactory.instance(DAOFactory.REST);
	private TempleDAO templeDAO;
	private Logger log;
	
	
	public TempleBO()
	{
		templeDAO = daoFactory.getTempleDAO();
		log = Logger.getLogger(this.getClass().getName());
	}
	
	private void auth() throws BOException
	{
		Session session = identityBO.initializeSession();
		templeDAO.setSession(session);
	}
	
	public Temple getTemple(Temple temple) throws BOException
	{
		// authenticate first
		auth();
		
		// temple cannot be null
		if( temple == null )
		{
			throw new BOException("bad", "bad"); // TODO set proper exception
			
		}
		
		if( temple.getCode() == null ||
				temple.getCode().equalsIgnoreCase( "" ))
		{
			throw new BOException("BO-0002", "Please set temple code in order to fetch the temple data"); // TODO set proper exception
		}
		
		Temple fetched = null;
		try {
			fetched = templeDAO.findById(temple.getCode());
		} catch (DAOException e) {
			// TODO swallow and log DAOException but throw BOException
			log.error(e.toString());
			throw new BOException("B0-0004", "No temple fetched due to DAO error. Please check logs."); // TODO set proper exception			
		}
		
		if( fetched == null )
		{
			throw new BOException("B0-0004", "No temple fetched."); // TODO set proper exception
		}
		
		return fetched;
		

	}

	public ArrayList<Temple> getTemples() throws BOException
	{
		
		// authenticate first
		auth();
		
		ArrayList<Temple> temples = null;
		try {
			temples = (ArrayList<Temple>) templeDAO.findAll();
		} catch (DAOException e) {
			// TODO swallow and log DAOException but throw BOException
			e.printStackTrace();
			throw new BOException("bad", "bad");
		}
		return temples;
		
	}
	
	public ArrayList<Temple> getTemples(Temple temple) throws BOException
	{
		/*
		 * The presence of the temple parameter signifies that
		 * we should return ALL data about ALL temples, which 
		 * means several passes over the API. First, to fetch
		 * the temple list. Next, to loop over the temple list
		 * and fetch the important information for each temple
		 */
		// authenticate first
		auth();
		
		ArrayList<Temple> temples = null;
		try {
			temples = (ArrayList<Temple>) templeDAO.findAll(temple);
		} catch (DAOException e) {
			// TODO swallow and log DAOException but throw BOException
			e.printStackTrace();
			throw new BOException("bad", "bad");
		}
		return temples;
		
	}	
}
